L09 Themes

Data Visualization (STAT 302)

Author

Lauren Kennedy

Published

October 23, 2024

Overview

The goal of this lab is to play around with the theme options in ggplot2.

Datasets

We’ll be using the cdc.txt and NU_admission_data.csv datasets.

Code
# load package(s)
library(tidyverse)
library(janitor)
library(ggthemes)
library(patchwork)
library(showtext)

# read in the cdc dataset
cdc <- read_delim(file = "data/cdc.txt", delim = "|") |>
  mutate(
    genhlth = factor(
      genhlth,
      levels = c("excellent", "very good", "good", "fair", "poor"),
      labels = c("Excellent", "Very Good", "Good", "Fair", "Poor")
      )
    )

# read in NU admission data
admin_dat <- read.csv("data/NU_admission_data.csv") %>% clean_names()


# set seed
set.seed(2468)

# selecting a random subset of size 100
cdc_small <- cdc |> 
  slice_sample(n = 100)

Exercise 1

Use the cdc_small dataset to explore several pre-set ggthemes. The code below constructs the familiar scatterplot of weight by height and stores it in plot_01. Display plot_01 to observe the default theme. Explore/apply, and display at least 7 other pre-set themes from the ggplot2 or ggthemes package. Don’t worry about making adjustments to the figures under the new themes. Just get a sense of what the themes are doing to the original figure plot_01.

There should be at least 8 plots for this task, plot_01 is pictured below. Use patchwork or cowplot in combination with R yaml chunk options fig-height and fig-width (out-width and fig-align may be useful as well) to setup the 8 plots together in a user friendly arrangement.

Code
# plot
plot_01 <- ggplot(
  data = cdc_small,
  aes(x = height, y = weight)
) +
  geom_point(size = 3, aes(shape = genhlth, color = genhlth)) +
  scale_y_continuous(
    name = "Weight in Pounds",
    limits = c(100, 275),
    breaks = seq(100, 275, 25),
    trans = "log10",
    labels = scales::label_number(
      accuracy = 1,
      suffix = " lbs"
    )
  ) +
  scale_x_continuous(
    name = "Height in Inches",
    limits = c(60, 80),
    breaks = seq(60, 80, 5),
    labels = scales::label_number(accuracy = 1, suffix = " in")
  ) +
  scale_shape_manual(
    name = "Health?",
    labels = c(
      "Excellent", "Very Good",
      "Good", "Fair", "Poor"
    ),
    values = c(17, 19, 15, 9, 4)
  ) +
  scale_color_brewer(
    name = "Health?",
    labels = c(
      "Excellent", "Very Good",
      "Good", "Fair", "Poor"
    ),
    palette = "Set1"
  ) +
  theme(
    legend.position = c(1, 0),
    legend.justification = c(1, 0)
  ) +
  labs(title = "CDC BRFSS: Weight by Height")
Solution
Code
plot_02 <- plot_01 + theme_dark()
plot_03 <- plot_01 + theme_void()
plot_04 <- plot_01 + theme_solarized()
plot_05 <- plot_01 +theme_excel()
plot_06 <- plot_01 + theme_tufte()
plot_07 <- plot_01 + theme(panel.grid.major = element_line(linewidth = 2))
plot_08 <- plot_01 + theme(panel.background = element_rect(fill = "linen"))

plot_01
plot_02
plot_03
plot_04
plot_05
plot_06
plot_07
plot_08

Important

Which theme or themes do you particularly like? Why?

Solution

I like theme_solarized() because it is something different and isn’t the stark white background that we are used to. Similarly, I like when the panel_background within the theme is set to linen - it is a nice, non-distracting background that highlights the points well. On a less distracting plot, setting the major gridlines to be thick, white lines might have a nice effect, but not on this plot.

Exercise 2

Using plot_01 from Exercise 1 and the theme() function, attempt to construct the ugliest plot possible (example pictured below). Be creative! It should NOT look exactly like the example. Since the goal is to understand a variety of adjustments, you should use a minimum of 10 different manual adjustments within theme().

Solution
Code
plot_01 + 
  theme(plot.background = element_rect(fill = "blue2", colour = NA),
        legend.background = element_rect(
          fill = "darkolivegreen1", 
          colour = "grey50", 
          linewidth = 1),
        panel.grid.major = element_line(linewidth = 2, color = "brown"),
        panel.background = element_rect(fill = "darkslateblue"),
        plot.title = element_text(face = "bold", colour = "red"),
        axis.title.x = element_text(color = "burlywood", size = 14),
        axis.title.y = element_text(color = "azure4", size = 14),
        axis.text.x = element_text(angle = 90, hjust = 0.5, color = "limegreen", size = 20),
        axis.text.y = element_text(face = "italic", color = "magenta", size = 18),
        legend.text = element_text(face = "bold", color = "orange", size = 25)
        )

Exercise 3

We will be making use of your code from Exercise 3 on L07 Layers. Using the NU_admission_data.csv you created two separate plots derived from the single plot depicted in undergraduate-admissions-statistics.pdf. Style these plots so they follow a “Northwestern” theme. You are welcome to display the plots separately OR design a layout that displays both together (likely one stacked above the other).

Check out the following webpages to help create your Northwestern theme:

Additional requirement:

Use a free non-standard font from google for the title. Pick one that looks similar to a Northwestern font.

Note

I find this blog post to be extremely useful for adding fonts. Important packages for using non-standard fonts are showtext, extrafont, extrafontdb, and sysfonts. The last 3 generally just need to be installed (not loaded per session).

Solution
Code
font_add("gothic_font", "CloisterBlack.ttf")
font_add("Georgia", regular = "/Library/Fonts/Georgia Italic.ttf")


showtext_auto()
bar_dat <- admin_dat %>%
  filter(year >= 2002) %>%
  mutate(
    cat_a = applications - admitted_students,
    cat_b = admitted_students - matriculants,
    cat_c = matriculants
  ) %>%
  select(year, contains("cat_")) %>%
  pivot_longer(
    cols = -year,
    names_to = "category",
    values_to = "value"
  )

bar_labels <- admin_dat %>%
  filter(year >= 2002) %>%
  select(-contains("rate")) %>%
  pivot_longer(
    cols = -year,
    names_to = "category",
    values_to = "value"
  ) %>%
  mutate(
    col_label = prettyNum(value, big.mark = ",")
  )

plot_1 <- ggplot(data = bar_dat, aes(factor(year), value)) +
  geom_col(aes(fill = category), width = 0.6, alpha = 0.7) +
  theme_minimal() +
  geom_text(
    data = bar_labels,
    aes(label = col_label),
    size = 2.5,
    color = "black",
    fontface = "bold"
  ) +
  labs(
    x = "Entering Year",
    y = "Applications",
    title = "Northwestern University \nUndergraduate Admissions 2001-2021"
  ) +
  theme(
    plot.title = element_text(family = "gothic_font", size = 20, face = "bold", hjust = 0.5),
    legend.position = "top",
    axis.title.x = element_text(family = "Georgia", face = "italic", size = 12),
    axis.title.y = element_text(family = "Georgia", face = "italic", size = 12),
    legend.text = element_text(family = "Georgia", face = "italic", size = 10)
) +
  scale_x_discrete(breaks = unique(bar_dat$year)) +
  
  scale_fill_manual(
    values = c("cat_a" = "#4E2A84", "cat_b" = "#836EAA", "cat_c" = "#E4E0EE"),
    labels = c("cat_a" = "Applications", "cat_b" = "Admitted students", "cat_c" = "Matriculants"),
               name = NULL)
  

rate_dat <- admin_dat %>%
  filter(year >= 2002) %>%
  select(year, contains("_rate")) %>%
  pivot_longer(
    cols = -year,
    names_to = "category", 
    values_to = "value"
  )

rate_labels <- admin_dat %>%
  filter(year >= 2002) %>%
  select(year, contains("_rate")) %>%
  pivot_longer(
    cols = -year,
    names_to = "category", 
    values_to = "value"
  ) %>%
  mutate(
    pct_label = str_c(value, '%'),
    value = case_when(
      category == "yield_rate" ~ value + 2, 
      category == "admission_rate" ~ value -2
    )
  )
  

plot_2 <- ggplot(data = rate_dat, aes(year, value)) +
  geom_line(aes(color = category)) +
  geom_point(data = rate_dat, 
             aes(color = category, shape = category),
             size = 2) +
  scale_shape_manual(values = c("yield_rate" = 8, "admission_rate" = 15),
                     labels = c("yield_rate" = "Yield Rate", "admission_rate" = "Admission Rate"),
                     name = NULL) +
  scale_color_manual(values = c("yield_rate" = "#4E2A84", "admission_rate" = "#E4E0EE"),
                     labels = c("yield_rate" = "Yield Rate", "admission_rate" = "Admission Rate"),
                     name = NULL) +
  theme_minimal() +
  geom_text(
    data = rate_labels,
    aes(label = pct_label),
    size = 2.5,
    color = "#716C6B",
    fontface = "bold"
  ) +
  labs(
    x = "Entering Year",
    y = "Rate",
    title = "Northwestern University \nUndergraduate Admissions 2001-2021") +
  theme(
    legend.position = 'top',
    panel.grid.minor.x = element_blank(),
    plot.title = element_text(family = "gothic_font", size = 20, face = "bold", hjust = 0.5),
    axis.title.x = element_text(family = "Georgia", face = "italic", size = 12),
    axis.title.y = element_text(family = "Georgia", face = "italic", size = 12),
    legend.text = element_text(family = "Georgia", face = "italic", size = 10)
  ) +
  scale_x_continuous(breaks = seq(2002, 2022, by = 1)) +
  scale_y_continuous(labels = function(x) paste0(x, "%"))

plot_1

Code
plot_2

Challenge

Important

Challenge is optional for all students, but we recommend trying it out!

Using cdc_small dataset, re-create your own version inspired by the plot below.

Must haves:

  • Use two non-standard fonts (one for labeling the point and the other for the axes)
  • Use at least two colors (one for the added point, another for the rest of the points)
  • A curved arrow used to label the point

Using Bilbo Baggins’ responses below to the CDC BRFSS questions, add Bilbo’s data point to a scatterplot of weight by height.

  • genhlth - How would you rate your general health? fair
  • exerany - Have you exercised in the past month? 1=yes
  • hlthplan - Do you have some form of health coverage? 0=no
  • smoke100 - Have you smoked at least 100 cigarettes in your life time? 1=yes
  • height - height in inches: 46
  • weight - weight in pounds: 120
  • wtdesire - weight desired in pounds: 120
  • age - in years: 45
  • gender - m for males and f for females: m
Note

Adding non-standard fonts can be an adventure. I find this blog post to be extremely useful for adding fonts. Important packages for using non-standard fonts are showtext, extrafont, extrafontdb, and sysfonts. The last 3 generally just need to be installed (not loaded per session).

Hint:

  • Create a new dataset (maybe call it bilbo or bilbo_baggins) using either data.frame() (base R - example in book) or tibble() (tidyverse - see help documentation for the function). Make sure to use variable names that exactly match cdc’s variable names. We have provided the tidyverse approach.
  • Search google fonts to find some free fonts to use (can get free fonts from other locations)
Solution
Code
# build dataset for Bilbo Baggins
bilbo <- tibble(
  genhlth  = "fair",
  exerany  = 1,
  hlthplan = 0,
  smoke100 = 1,
  height   = 46,
  weight   = 120,
  wtdesire = 120,
  age      = 45,
  gender   = "m"
)